#!/bin/bash

# MarkEdit 构建脚本

set -e

echo "开始构建 MarkEdit..."

# 检查Go环境
if ! command -v go &> /dev/null; then
    echo "错误: 未找到Go环境，请先安装Go"
    exit 1
fi

# 检查Go版本
GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
REQUIRED_VERSION="1.19"

if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$GO_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
    echo "错误: Go版本需要 >= $REQUIRED_VERSION，当前版本: $GO_VERSION"
    exit 1
fi

# 设置环境变量
export CGO_ENABLED=0
export GOOS=${GOOS:-linux}
export GOARCH=${GOARCH:-amd64}

# 创建构建目录
BUILD_DIR="build"
mkdir -p $BUILD_DIR

echo "正在下载依赖..."
go mod download
go mod verify

echo "正在运行测试..."
go test ./...

echo "正在构建应用..."
go build -a -installsuffix cgo -ldflags="-w -s" -o $BUILD_DIR/markedit ./cmd/server

echo "正在复制资源文件..."
cp -r config $BUILD_DIR/
cp -r web $BUILD_DIR/

echo "构建完成！"
echo "可执行文件: $BUILD_DIR/markedit"
echo "配置文件: $BUILD_DIR/config/"
echo "静态文件: $BUILD_DIR/web/"

# 创建启动脚本
cat > $BUILD_DIR/start.sh << 'EOF'
#!/bin/bash
cd "$(dirname "$0")"
./markedit
EOF

chmod +x $BUILD_DIR/start.sh

echo "启动脚本: $BUILD_DIR/start.sh"
echo ""
echo "使用方法:"
echo "  cd $BUILD_DIR"
echo "  ./start.sh"